package com.example.zzh.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.zzh.entity.ZzhFunction;
import com.example.zzh.entity.ZzhOrganization;
import com.example.zzh.entity.ZzhRole;
import com.example.zzh.entity.ZzhStaff;
import com.example.zzh.mapper.ZzhFunctionMapper;
import com.example.zzh.service.ZzhFunctionService;
import com.example.zzh.service.ZzhStaffService;
import com.example.zzh.utils.Result;
import com.example.zzh.utils.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.update;

/**
 * <p>
 * 功能模块表 前端控制器
 * </p>
 *
 * @author zzh
 * @since 2023-07-28
 */
@Api(tags = "菜单配置")
@RestController
@RequestMapping("/zzh-function")
public class ZzhFunctionController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ZzhFunctionService ZzhFunctionService;

    @PostMapping("/list")
    @ApiOperation(value = "查询所有菜单", notes = "查询所有菜单")
    public Result findeByLoginName(){
        // 获取Session对象
        HttpSession session = request.getSession();
        // 将用户信息存储到Session中
        ZzhStaff zzhStaff=(ZzhStaff) session.getAttribute("user");
        List<ZzhFunction> list=ZzhFunctionService.list();
        List<Map<String, Object>> treeData = new ArrayList<>();
        Map<String, Map<String, Object>> map = new HashMap<>();
        //遍历每个菜单
        for(int i=0;i<list.size();i++){
            ZzhFunction arrayList=list.get(i);
            Map<String,Object> node=new HashMap<>();
            node.put("id",arrayList.getId());
            node.put("number",arrayList.getNumber());
            node.put("name",arrayList.getName());
            node.put("icon",arrayList.getIcon());
            node.put("url",arrayList.getUrl());
            node.put("component",arrayList.getComponent());
            node.put("urlname",arrayList.getType());
            // 将节点存储到map中，以便后续构建树形结构
            map.put(arrayList.getNumber(), node);
            boolean flag=false;
            String[] temp;
            String delimiter = ",";// 指定分割字符
            String pushBtn=arrayList.getPushBtn();
            temp = pushBtn.split(delimiter);// 分割字符串
            //遍历菜单中的pushBtn按钮权限
            for (int j = 0; j < temp.length; j++) {
                if(temp[j].equals(zzhStaff.getPosition())){
                    flag=true;
                }
            }
            if(flag){
                //判断父id不为空和不为0
                if(arrayList.getParentNumber() != null && !"0".equals(arrayList.getParentNumber())){
                    Map<String, Object> parent = map.get(arrayList.getParentNumber());
                    if (parent != null) {
                        List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
                        if (children == null) {
                            children = new ArrayList<>();
                            parent.put("children", children);
                        }
                        children.add(node);
                    }
                } else {
                    treeData.add(node); // 如果节点没有父节点，则将其作为根节点添加到treeData中
                }
            }
        }
        return ResultGenerator.genSuccessResult(treeData);
    }

    @PostMapping("/findeByList")
    @ApiOperation(value = "查询所有菜单", notes = "查询所有菜单")
    public Result findeByList(){
        // 获取Session对象
        HttpSession session = request.getSession();
        // 将用户信息存储到Session中
        ZzhStaff zzhStaff=(ZzhStaff) session.getAttribute("user");
        List<ZzhFunction> list=ZzhFunctionService.list();
        List<Map<String, Object>> treeData = new ArrayList<>();
        Map<String, Map<String, Object>> map = new HashMap<>();
        //遍历每个菜单
        for(int i=0;i<list.size();i++){
            ZzhFunction arrayList=list.get(i);
            Map<String,Object> node=new HashMap<>();
            node.put("id",arrayList.getId());
            node.put("number",arrayList.getNumber());
            node.put("name",arrayList.getName());
            node.put("icon",arrayList.getIcon());
            node.put("url",arrayList.getUrl());
            node.put("component",arrayList.getComponent());
            node.put("urlname",arrayList.getType());
            // 将节点存储到map中，以便后续构建树形结构
            map.put(arrayList.getNumber(), node);
            boolean flag=false;
            String[] temp;
            String delimiter = ",";// 指定分割字符
            String pushBtn=arrayList.getPushBtn();
            temp = pushBtn.split(delimiter);// 分割字符串
            //遍历菜单中的pushBtn按钮权限
            for (int j = 0; j < temp.length; j++) {
                if(temp[j].equals(zzhStaff.getPosition())){
                    flag=true;
                }
            }
            flag=true;
            if(flag){
                //判断父id不为空和不为0
                if(arrayList.getParentNumber() != null && !"0".equals(arrayList.getParentNumber())){
                    Map<String, Object> parent = map.get(arrayList.getParentNumber());
                    if (parent != null) {
                        List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
                        if (children == null) {
                            children = new ArrayList<>();
                            parent.put("children", children);
                        }
                        children.add(node);
                    }
                } else {
                    treeData.add(node); // 如果节点没有父节点，则将其作为根节点添加到treeData中
                }
            }
        }
        return ResultGenerator.genSuccessResult(treeData);
    }

    @PostMapping("/findeByIdList")
    @ApiOperation(value = "查询角色id的所有功能", notes = "查询角色id的所有功能")
    public Result findeByIdList(@RequestParam int roleId){
        ArrayList<Long> pushBtns=new ArrayList<>();
        List<ZzhFunction> zzhFunctionList=ZzhFunctionService.list();
        for(ZzhFunction zzhFunction : zzhFunctionList ){
            String[] temp;
            String delimiter = ",";// 指定分割字符
            String pushBtn=zzhFunction.getPushBtn();
            temp = pushBtn.split(delimiter);// 分割字符串
            for (int i = 0; i < temp.length; i++) { //for 循环
                if(temp[i].equals(String.valueOf(roleId))){
                    pushBtns.add(zzhFunction.getId());
                }
            }
        }
        System.out.println(pushBtns);
        return ResultGenerator.genSuccessResult(pushBtns);
    }

    @PostMapping("/pushBtn")
    @ApiOperation(value = "分配角色按钮", notes = "分配角色按钮")
    public Result pushBtn(@RequestBody Map<String,Object> params){
        if (StringUtils.isEmpty(params.get("id")) || StringUtils.isEmpty(params.get("ids"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        //角色id
        int roleId= (int) params.get("id");
        //选中的菜单按钮
        ArrayList<Integer> ids= (ArrayList) params.get("ids");
        System.out.println(roleId);
        System.out.println(ids);
        ArrayList<Long> pushBtns=new ArrayList<>();
        String[] temp;
        String delimiter = ",";// 指定分割字符
        //查询所有菜单信息
        List<ZzhFunction> zzhFunctionList=ZzhFunctionService.list();
        //遍历所有菜单信息
        for(ZzhFunction zzhFunction : zzhFunctionList ){
            String pushBtn=zzhFunction.getPushBtn();
            //分割pushBtn字符串
            temp = pushBtn.split(delimiter);
            System.out.println(Arrays.toString(temp));
            boolean flag=true;
            //遍历选中的菜单信息
            for(int id : ids){
                //选中的菜单
                if(zzhFunction.getId()==id){
                    boolean flagPushBtns=true;
                    for (int i = 0; i < temp.length; i++) { //for 循环
                        if(temp[i].equals(String.valueOf(roleId))){
                            flagPushBtns=false;
                        }
                    }
                    if(flagPushBtns){
                        String pushBtnNew=pushBtn+","+roleId;
                        UpdateWrapper<ZzhFunction> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.set("push_btn",pushBtnNew);
                        updateWrapper.eq("id",zzhFunction.getId());
                        boolean result = ZzhFunctionService.update(updateWrapper);
                    }
                    flag=false;
                    break;
                }
            }
            //未选中的菜单
            if(flag){
                String pushBtnNew="";
                //遍历字符串pushBtn数组
                for (int i = 0; i < temp.length; i++) {
                    //如果角色id在字符串pushBtn数组中就清除
                    if(!temp[i].equals(String.valueOf(roleId))){
                        pushBtns.add(zzhFunction.getId());
                        if(i==0){
                            pushBtnNew=temp[i];
                        }else {
                            pushBtnNew=pushBtnNew+","+temp[i];
                        }
                    }
                }
                UpdateWrapper<ZzhFunction> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("push_btn",pushBtnNew);
                updateWrapper.eq("id",zzhFunction.getId());
                boolean result = ZzhFunctionService.update(updateWrapper);
            }
        }
        return ResultGenerator.genSuccessResult();
    }
}